﻿using System;
using System.Linq;

namespace Battle.Net.Infrastructure
{
    internal static class Extensions
    {
       
        internal static string ToEnumString(this Enum value)
        {
            var info = value.GetType().GetField(value.ToString());
            var stringValue = info.GetCustomAttributes(typeof (StringValue), false).SingleOrDefault() as StringValue;
            
            return stringValue != null ? stringValue.Value : Enum.GetName(value.GetType(), value);
        }

        internal static T FromEnumString<T>(this string enumString)
            where T: struct
        {
            var fields = typeof (T).GetFields();
            foreach (var info in fields)
            {
                var stringValue = info.GetCustomAttributes(typeof(StringValue), false).SingleOrDefault() as StringValue;
                if (stringValue != null && stringValue.Value == enumString)
                {
                    var enumId = (int)info.GetRawConstantValue();
                    return (T)Enum.ToObject(typeof (T), enumId);
                }
            }

            return Activator.CreateInstance<T>();
        }

        internal static DateTime FromUnixTimestamp(this string value)
        {
            Int64 ticks = 0;
            var result = Int64.TryParse(value, out ticks);
            if (result)
            {
                var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                origin = origin.AddMilliseconds(ticks);
                return origin;
            }
            return new DateTime(1970, 1, 1, 0, 0, 0, 0);
        }

    }
}
